<template>
  <el-config-provider :locale="locale" :size="assemblySize" :button="buttonConfig">
    <router-view></router-view>
    <AddEventMask ref="addEventMask"></AddEventMask>
    <DetailsMask ref="detailsMask"></DetailsMask>
    <DetailsMaskCi ref="detailsMaskCi"></DetailsMaskCi>
    <el-dialog title="来电显示" v-model="dialogTableVisible" class="customMsgCls">
      <div :style="{ height: '500px' }">
        <div class="common-layout">
          <el-container style="width: 100%; height: 100%">
            <el-header style="width: 100%; height: 20px">
              <el-row>
                <el-col :span="6">
                  <el-button @click="addEvent()">快捷添加请求</el-button>
                </el-col>
                <el-col :span="12">
                  <p style="font-size: 20px; text-align: center">拨入电话号码:{{ tanpingNumber }}</p>
                </el-col>
              </el-row>
            </el-header>
            <el-container>
              <!-- <el-aside style="width: 200px; height: 100px"> 左边</el-aside> -->
              <el-main>
                <el-tabs v-model="activeName" @tab-click="handleClickTab">
                  <el-tab-pane label="详细信息" name="first">
                    <table>
                      <tr>
                        <td>所属机构</td>
                        <td>{{ form.orgName }}</td>
                      </tr>
                      <tr>
                        <td>用户状态</td>
                        <td>{{ form.userState }}</td>
                      </tr>
                      <tr>
                        <td>性别</td>
                        <td>{{ form.sex }}</td>
                      </tr>
                      <tr>
                        <td>姓氏</td>
                        <td>{{ form.firstName }}</td>
                      </tr>
                      <tr>
                        <td>用户名字</td>
                        <td>{{ form.lastName }}</td>
                      </tr>
                      <tr>
                        <td>用户职称</td>
                        <td>{{ form.nun }}</td>
                      </tr>
                      <tr>
                        <td>职务</td>
                        <td>{{ form.nun }}</td>
                      </tr>
                      <tr>
                        <td>证件号</td>
                        <td>{{ form.nun }}</td>
                      </tr>
                      <tr>
                        <td>姓名拼音</td>
                        <td>{{ form.pinyin }}</td>
                      </tr>
                      <tr>
                        <td>生日</td>
                        <td>{{ form.birthday }}</td>
                      </tr>
                      <tr>
                        <td>邮件</td>
                        <td>{{ form.email }}</td>
                      </tr>
                      <tr>
                        <td>手机号</td>
                        <td>{{ form.moblie }}</td>
                      </tr>
                      <tr>
                        <td>电话</td>
                        <td>{{ form.phone }}</td>
                      </tr>
                    </table>
                  </el-tab-pane>

                  <el-tab-pane label="关联配置项" name="second">
                    <div :style="{ height: '400px' }">
                      <ProTable
                        ref="proTableCi"
                        :columns="columnsCi"
                        :request-api="getTableListCi"
                        :init-param="initParamCi"
                        :data-callback="dataCallbackCi"
                        :request-auto="false"
                      >
                        <template #operation="scope">
                          <el-button type="primary" link :icon="View" @click="seeDetailsCi(scope.row)">查看</el-button>
                        </template>
                      </ProTable>
                    </div>
                  </el-tab-pane>

                  <el-tab-pane label="关联请求" name="three">
                    <div :style="{ height: '400px' }">
                      <ProTable
                        ref="proTable"
                        :columns="columns"
                        :request-api="getTableList"
                        :init-param="initParam"
                        :data-callback="dataCallback"
                        :request-auto="false"
                      >
                        <template #operation="scope">
                          <el-button type="primary" link :icon="View" @click="seeDetails(scope.row)">查看</el-button>
                        </template>
                      </ProTable>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </el-main>
            </el-container>
          </el-container>
        </div>
      </div>
    </el-dialog>
  </el-config-provider>
</template>

<script setup lang="ts">
import { onMounted, reactive, computed, ref } from "vue";
import { useI18n } from "vue-i18n";
import { getBrowserLang } from "@/utils";
import { useTheme } from "@/hooks/useTheme";
import { ElConfigProvider } from "element-plus";
import { LanguageType } from "./stores/interface";
import { useGlobalStore } from "@/stores/modules/global";
import en from "element-plus/es/locale/lang/en";
import zhCn from "element-plus/es/locale/lang/zh-cn";

import { useUserStore } from "@/stores/modules/user";

import WebSocket from "@/api/modules/websocket";
import { getPpbxToken, findUserByNumber, createLYRequest } from "@/api/modules/index";
import { findUserDetail, resetPassword, getCurrentLoginUser } from "@/api/modules/accessController";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { findPageRequests } from "@/api/modules/request";
import { findPageConfigureItemByUser } from "@/api/modules/assetManagement";

import { useRouter } from "vue-router";
import { ElMessageBox } from "element-plus";

import AddEventMask from "@/views/eventManagement/components/AddEventMask.vue";
import DetailsMask from "@/components/Event/DetailsMask.vue";
import DetailsMaskCi from "@/components/Asset/DetailsMask.vue";
import { View } from "@element-plus/icons-vue";
const router = useRouter();
const globalStore = useGlobalStore();

// init theme
const { initTheme } = useTheme();
initTheme();

// init language
const i18n = useI18n();

// ProTable 实例
const proTable = ref<ProTableInstance>();
const initParam = reactive({});
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "eno";
  newParams.sord = "desc";
  newParams.createdByName = form.loginName == "" ? null : form.loginName;
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findPageRequests(newParams, "requestQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};
// dataCallback 是对于返回的表格数据做处理
const dataCallback = (data: any) => {
  // loading.value = false;
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { prop: "requestCode", label: "编号", width: 160 },
  { prop: "etitle", label: "标题", width: 260 },
  { prop: "statusName", label: "状态", width: 100 },
  { prop: "createdOn", label: "创建时间", width: 260 },
  { prop: "operation", label: "操作", fixed: "right", width: 80 }
]);
const proTableCi = ref<ProTableInstance>();
const initParamCi = reactive({});
const getTableListCi = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "ciId";
  newParams.sord = "desc";
  newParams.loginName = form.fullName == "" ? null : form.fullName;
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findPageConfigureItemByUser(newParams, "ciQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};
// dataCallback 是对于返回的表格数据做处理
const dataCallbackCi = (data: any) => {
  // loading.value = false;
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
// 表格配置项
const columnsCi = reactive<ColumnProps<resList>[]>([
  { prop: "categoryName", label: "分类", width: 160 },
  { prop: "cino", label: "编号", width: 160 },
  { prop: "ciname", label: "名称", width: 260 },
  { prop: "status", label: "状态", width: 160 },
  { prop: "operation", label: "操作", fixed: "right", width: 80 }
]);
export interface resList {
  requestCode: string;
  etitle: string;
  statusName: string;
  createdOn: string;
  categoryName: string;
  cino: string;
  ciname: string;
  status: string;
}

const handleClickTab = (tab: any, event: Event) => {
  if (tab.props.label == "关联请求") {
    proTable.value?.getTableList();
  }
  if (tab.props.label == "关联配置项") {
    proTableCi.value?.getTableList();
  }
  console.log(tab, event);
};
// 添加事件
const addEventMask = ref();
const addEvent = () => {
  let item = {
    isTanpingAdd: "true",
    // companyNo:form.companyNo,
    userId: form.userId,
    fullName: form.fullName
  };

  // tanping("1001")
  addEventMask.value.open(item);
};
// 查看详情
const detailsMask = ref();
const seeDetails = (item: { eno: any }) => {
  detailsMask.value.open(item);
};

// 查看详情
const detailsMaskCi = ref();
const seeDetailsCi = (item: any) => {
  detailsMaskCi.value.open(item);
};
const dialogTableVisible = ref(false);
const tanping = (data: string) => {
  //addEventMask.value.open(null);
  //detailsMask.value.open({eno:179});
  tanpingNumber.value = data;
  findUserByNumber(data).then(res => {
    // if(res.data!=undefined){
    // 	for(let i=1;i<res.data.length;i++){

    // 	}
    // }
    if ((res.data as any).length >= 1) {
      console.log("fffffffffffff");
      let newRes = JSON.parse(JSON.stringify((res.data as any)[0]));
      console.log(newRes);
      // lcallCodeOper=newRes.lcallCodeOper
      form.orgName = newRes.orgName;
      form.userState = newRes.userState == true ? "启用" : "禁用";
      form.sex = newRes.sex == true ? "男" : "女";
      form.firstName = newRes.firstName;
      form.lastName = newRes.lastName;
      form.loginName = newRes.loginName;
      form.pinyin = newRes.pinyin;
      form.birthday = newRes.birthday;
      form.email = newRes.email;
      form.moblie = newRes.moblie;
      form.phone = newRes.phone;
      form.fullName = newRes.fullName;
      form.userId = newRes.userId;
    } else {
      form.orgName = "";
      form.userState = "";
      form.sex = "";
      form.firstName = "";
      form.lastName = "";
      form.loginName = "";
      form.pinyin = "";
      form.birthday = "";
      form.email = "";
      form.moblie = "";
      form.phone = "";
      form.fullName = "";
      form.userId = "";
      console.log("2222222222");
    }

    // console.log(res.data.length)
  });
  console.log("弹屏1111111111111111111111111");
  // const userStore = useUserStore();

  // ElMessageBox.confirm("您当前页面将不保留，确定前往请求添加界面？", "提示", {
  //   confirmButtonText: "确定",
  //   cancelButtonText: "取消",
  //   type: "warning",
  //   center: true
  // })
  //   .then(() => {
  //     if (userStore.menuFlag == "index") {
  //     	router.push("/eventManagement/index?type=add");
  //     }else{
  //     	//router.push("/goback/index?isTanping=1&eno=179");
  //     	router.push("/goback/index?isTanping=1&type=add");
  //     }
  //   })
  //   .catch(() => {
  //     ElMessage({
  //       type: "info",
  //       message: "取消操作"
  //     });
  //   });
  dialogTableVisible.value = true;
};

const form = reactive({
  orgName: "",
  userState: "",
  sex: "",
  firstName: "",
  lastName: "",
  nun: "",
  loginName: "",
  pinyin: "",
  birthday: "",
  email: "",
  moblie: "",
  phone: "",
  fullName: "",
  userId: ""
});
const activeName = ref("first");
const intervalTimer = ref();
const tanpingNumber = ref("");
onMounted(() => {
  const language = globalStore.language ?? getBrowserLang();
  i18n.locale.value = language;
  globalStore.setGlobalState("language", language as LanguageType);

  if (localStorage.getItem("token")) {
    const userStore = useUserStore();
    userStore.setToken(localStorage.getItem("token") || "");
    userStore.setUsername(localStorage.getItem("username"));
  }

  //来电弹屏开始
  // tanping("13025566666")
  let lcallCodeOper = "5503301";
  let role = "";
  let token = "";
  let ipAndPort = "";
  if (localStorage.getItem("token")) {
    getCurrentLoginUser().then(res => {
      let newRes = JSON.parse(JSON.stringify(res));
      console.log(newRes);
      lcallCodeOper = newRes.lcallCodeOper;
      // form.orgName=newRes.orgName
      // form.userState=newRes.userState==true?"启用":"禁用";
      // form.sex=newRes.sex==true?"男":"女";
      // form.firstName=newRes.firstName
      // form.lastName=newRes.lastName
      // form.loginName=newRes.loginName
      // form.pinyin=newRes.pinyin
      // form.birthday=newRes.birthday
      // form.email=newRes.email
      // form.moblie=newRes.moblie
      // form.phone=newRes.phone

      if (newRes.userRoles != undefined && newRes.userRoles.length > 0) {
        let roleFlag = false;
        (newRes.userRoles as any).forEach(function (element) {
          if (element.roleCode == "ROLE_HELPDESKENGINEER") {
            roleFlag = true;
          }
        });
        if (roleFlag) {
          //弹屏程序启动
          console.log("弹屏程序启动");
          let webSocketUrl = "ws://192.168.1.203:8889/api/buletooth";
          getPpbxToken().then(res => {
            if (res != null && res != undefined) {
              let jsondata = JSON.parse(res.toString());
              token = jsondata.token;
              ipAndPort = jsondata.ipAndPort;
              console.log(token);
              console.log(ipAndPort);
              webSocketUrl = "wss://" + ipAndPort + "/openapi/v1.0/subscribe?access_token=" + token;
              WebSocket.webSocketInit(webSocketUrl); //初始化webSocket

              WebSocket.setOpenCallback(res => {
                WebSocket.sendMessage('\{"topic_list":[30011]}');
                intervalTimer.value = setInterval(() => {
                  let currentDate = new Date();
                  let year = currentDate.getFullYear();
                  let month = currentDate.getMonth() + 1;
                  let day = currentDate.getDate();
                  let hour = currentDate.getHours();
                  let minute = currentDate.getMinutes();
                  let second = currentDate.getSeconds();
                  console.log("发送heartbeat在：");
                  console.log(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
                  WebSocket.sendMessage("heartbeat");
                  console.log("heartbeat成功", res);
                  // 在这里写定时器执行的代码
                }, 40000);

                console.log("连接建立成功", res);
              });
              WebSocket.setMessageCallback(res => {
                console.log("接收到回信", res);
                //前端判断弹屏开始
                let data;
                if (res.data != null && res.data != "heartbeat response") {
                  data = JSON.parse(res.data);
                  // if (data.type != null) {
                  // 	$.ajax({
                  // 		type: "post",
                  // 		data:{
                  // 			"data": event.data
                  // 		},
                  // 		url: "ppbxInfo!receiptPPbxInfo.action",
                  // 		success: function (data) {
                  // 		}
                  // 	})
                  // }
                  //前端判断弹屏开始
                  let fromnum = "";
                  let tonum = "";
                  let member_status = "";
                  let BYEflag = "";
                  let BYEfalg2 = "";

                  let inboundmember_status = "";
                  let fromNumber = "";
                  let toNumber = "";

                  //数据
                  if (data.msg.members != null) {
                    console.log(data.msg.members);
                    data.msg.members.forEach(function (element) {
                      console.log(element);
                      let map = element;
                      //内线呼入方法
                      if (map.extension != null) {
                        member_status = map.extension.member_status;
                        if (member_status != null && member_status != "" && member_status == "BYE") {
                          //判断是否为挂断，如果挂断查询录音并生成工单
                          BYEflag = "yes";
                        }

                        if (member_status != null && member_status != "" && member_status == "ANSWER") {
                          //判断是否为挂断，如果挂断查询录音并生成工单
                          BYEfalg2 = "yes";
                          tonum = map.to;
                        }
                        if (member_status != null && member_status != "" && member_status == "ANSWERED") {
                          BYEfalg2 = "yes";
                          fromnum = map.from;
                        }
                      }

                      //外线呼入方法
                      if (map.inbound != null) {
                        fromNumber = map.inbound.from;
                        toNumber = map.inbound.to;
                        inboundmember_status = map.inbound.member_status;
                      }

                      console.log(tonum);
                      console.log(fromnum);
                      console.log(fromNumber);
                      console.log(toNumber);
                      console.log(inboundmember_status);
                      if (tonum != "" && fromnum != "" && tonum == lcallCodeOper) {
                        console.log("内线呼入弹屏");
                        tanping(fromnum);
                        //内线呼入
                        //setMessageInnerHTML(fromnum);
                      }
                      if (fromNumber != "" && toNumber != "" && inboundmember_status == "ANSWERED" && toNumber == lcallCodeOper) {
                        console.log("外线呼入弹屏");
                        tanping(fromNumber);
                        //外线呼入
                        // setMessageInnerHTML(fromNumber);
                      }
                      if (BYEflag != "" && BYEfalg2 !== "") {
                        //生成录音工单
                        createLYRequest().then(res => {
                          console.log("录音返回");
                        });
                      }
                      if (inboundmember_status == "BYE") {
                        //外线呼入生成录音工单
                        //生成录音工单
                        createLYRequest().then(res => {
                          console.log("录音返回");
                        });
                      }
                    });
                  }
                  //前端弹屏结束
                }
              });
              WebSocket.setCloseCallback(res => {
                WebSocket.webSocketInit(webSocketUrl);
                clearInterval(intervalTimer.value);
                console.log("连接关闭", res);
              });
              WebSocket.setErrorCallback(res => {
                // WebSocket.webSocketInit(webSocketUrl);
                // console.log("连接发生错误", res);
              });

              //来电弹屏结束
            }
            console.log(webSocketUrl);
          });
        }
      }
    });
  }
});

// element language
const locale = computed(() => {
  if (globalStore.language == "zh") return zhCn;
  if (globalStore.language == "en") return en;
  return getBrowserLang() == "zh" ? zhCn : en;
});

// element assemblySize
const assemblySize = computed(() => globalStore.assemblySize);

// element button config
const buttonConfig = reactive({ autoInsertSpace: false });
</script>

<style lang="scss">
.weiyi {
  top: 20px !important;
}
.table-data-box {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  margin-bottom: 15px;
  border-top: 1px solid #ebeef5;
  border-left: 1px solid #ebeef5;
  &::before {
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 100%;
    content: "";
    border-right: 1px solid #ebeef5;
  }
  &::after {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 0;
    content: "";
    border-bottom: 1px solid #ebeef5;
  }
  .data-cell {
    box-sizing: border-box;
    display: flex;
    align-items: stretch;
    width: 50%;
    background-color: rgb(245 247 250);
    border-right: 1px solid #ebeef5;
    border-bottom: 1px solid #ebeef5;
    &:hover {
      background-color: rgb(245 247 250);
      .label {
        background-color: rgb(245 247 250);
      }
      .content {
        background-color: rgb(245 247 250);
      }
    }
    &.row {
      width: 100%;
    }
  }
  .label {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    padding: 8px 10px;
    font-weight: bold;
    color: #333333;
    text-align: center;
  }
  .w-100 {
    width: 100px;
  }
  .w-110 {
    width: 110px;
  }
  .w-120 {
    width: 120px;
  }
  .w-130 {
    width: 130px;
  }
  .w-140 {
    width: 140px;
  }
  .w-150 {
    width: 150px;
  }
  .w-160 {
    width: 160px;
  }
  .w-170 {
    width: 170px;
  }
  .w-180 {
    width: 180px;
  }
  .w-190 {
    width: 190px;
  }
  .w-200 {
    width: 200px;
  }
  .content {
    box-sizing: border-box;
    flex: 1;
    min-height: 37px;
    max-height: 300px;
    padding: 8px 10px;
    overflow: hidden;
    overflow-y: auto;
    line-height: 1.5;
    word-break: break-all;
    word-wrap: break-word;
    background-color: #ffffff;
    border-left: 1px solid #ebeef5;
  }
}
.customMsgCls {
  z-index: 9999; /* 设置一个高的 z-index 值 */
}
.customMsgCls2 {
  z-index: 2000; /* 设置一个高的 z-index 值 */
}
</style>
